using System;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace NikCodes.SharePoint.ClientSide
{
    public class ScriptsCodeBehind : UserControl
    {
        protected Literal JQueryScript;
        protected Literal PrototypeScript;
        protected Literal JQueryUICoreScript;
        protected Literal JQueryUIEffectsScript;
        protected Literal JQueryUIInteractionScript;
        protected Literal JQueryUIWidgitScript;
        protected Literal ScriptaculousScript;
        protected Literal ExtScript;

        public ScriptsCodeBehind()
        {
            Load += OnLoad;
        }

        private void OnLoad(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SPPropertyBag props = SPContext.Current.Web.Properties;

                JQueryScript.Visible = Utilities.IsSet(props, "JQuery");
                PrototypeScript.Visible = Utilities.IsSet(props, "Prototype");
                JQueryUICoreScript.Visible = Utilities.IsSet(props, "JQueryUICore");
                JQueryUIEffectsScript.Visible = Utilities.IsSet(props, "JQueryUIEffects");
                JQueryUIInteractionScript.Visible = Utilities.IsSet(props, "JQueryUIInteraction");
                JQueryUIWidgitScript.Visible = Utilities.IsSet(props, "JQueryUIWidgit");
                ExtScript.Visible = Utilities.IsSet(props, "Ext");

                SetScriptaculous(props);
            }
        }

        private void SetScriptaculous(SPPropertyBag props)
        {
            if (Utilities.IsSet(props, "Scriptaculous"))
            {
                ScriptaculousScript.Text =
                    "<script type=\"text/javascript\" src=\"/_layouts/ClientSide/scriptaculous.js";

                string addLibs = "";

                if (Utilities.IsSet(props, "ScriptaculousBuilder"))
                    addLibs += "builder,";
                if (Utilities.IsSet(props, "ScriptaculousEffects"))
                    addLibs += "effects,";
                if (Utilities.IsSet(props, "ScriptaculousDragDrop"))
                    addLibs += "dragdrop,";
                if (Utilities.IsSet(props, "ScriptaculousControls"))
                    addLibs += "controls,";
                if (Utilities.IsSet(props, "ScriptaculousSlider"))
                    addLibs += "slider,";

                if (!string.IsNullOrEmpty(addLibs))
                    ScriptaculousScript.Text += "?load=" + addLibs.Substring(0, addLibs.Length - 1);

                ScriptaculousScript.Text += "\"></script>";
            }
        }
    }
}
